<template>
  <div :class="level > 1 ? 'va-menu-sub' : 'va-menu'" :style="{width: width}">
    <ul v-for="menu in menus" :class="ulClass">
      <va-menu-item :menu="menu" :level="level" @menu-active="onMenuActive"></va-menu-item>
    </ul>
  </div>
</template>

<script>
  export default {
    props: {
      menus: {
        type: Array,
        default () {
          return []
        }
      },
      /* 暂时只能配置 width 属性，默认为240px */
      config: {
        default () {
          return {}
        }
      },
      /* 以下属性使用时不传 */
      level: {
        type: Number,
        default () {
          return 1
        }
      }
    },
    beforeCreate () {
      this.$options.components.VaMenuItem = require('./VaMenuItem.vue').default
    },
    data () {
      return {
        tmpMenu: null
      }
    },
    computed: {
      width () {
        return this.level > 1 ? null : (this.config && this.config.width) || '240px'
      },
      ulClass () {
        return `va-menu-lv-${this.level}`
      }
    },
    methods: {
      resetActiveState (menus, parent) {
        for (let menu of menus) {
          if (parent && !menu._parent) {
            menu._parent = parent
          }
          if (menu.link && this.$route.path.indexOf(menu.link) === 0) {
            this.tmpMenu = menu
          } else {
            this.$set(menu, 'expanded', false)
          }
          this.$set(menu, 'active', false)
          if (menu.children && menu.children.length > 0) {
            this.resetActiveState(menu.children, menu)
          }
        }
      },
      refreshActiveState () {
        this.tmpMenu = null
        this.resetActiveState(this.menus)
        if (this.tmpMenu) {
          this.$set(this.tmpMenu, 'active', true)
          this.expanedParent(this.tmpMenu)
        }
      },
      expanedParent (child) {
        if (child._parent) {
          this.$set(child._parent, 'expanded', true)
          this.expanedParent(child._parent)
        }
      },
      onMenuActive () {
        this.$emit('menu-active')
      }
    },
    mounted () {
      this.refreshActiveState()
    },
    watch: {
      '$route' () {
        this.refreshActiveState()
      },
      menus () {
        this.refreshActiveState()
      }
    }
  }
</script>
